<template>
  <div class="admin-dashboard">
    <el-row :gutter="20">
      <!-- 数据概览卡片 -->
      <el-col :xs="24" :sm="12" :md="6" v-for="(card, index) in statCards" :key="index">
        <el-card class="stat-card" shadow="hover" :style="{ 'background-color': card.bgColor }">
          <div class="stat-icon">
            <el-icon><component :is="card.icon" /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ card.value }}</div>
            <div class="stat-label">{{ card.label }}</div>
          </div>
          <div class="stat-progress">
            <el-progress :percentage="card.progress" :stroke-width="6" :show-text="false" />
            <div class="progress-text">
              <span>{{ card.progressText }}</span>
              <span class="trend" :class="card.trend >= 0 ? 'up' : 'down'">
                <el-icon v-if="card.trend >= 0"><CaretTop /></el-icon>
                <el-icon v-else><CaretBottom /></el-icon>
                {{ Math.abs(card.trend) }}%
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-row">
      <!-- 订单趋势 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>订单趋势</span>
              <div class="card-actions">
                <el-radio-group v-model="orderChartType" size="small">
                  <el-radio-button label="week">周</el-radio-button>
                  <el-radio-button label="month">月</el-radio-button>
                  <el-radio-button label="year">年</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart-placeholder">
            <div class="placeholder-text">订单趋势图表</div>
          </div>
        </el-card>
      </el-col>

      <!-- 用户统计 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>用户统计</span>
              <div class="card-actions">
                <el-radio-group v-model="userChartType" size="small">
                  <el-radio-button label="role">角色</el-radio-button>
                  <el-radio-button label="growth">增长</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart-placeholder">
            <div class="placeholder-text">用户统计图表</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="table-row">
      <!-- 最近订单 -->
      <el-col :xs="24" :lg="12">
        <el-card class="table-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最近订单</span>
              <el-button text @click="viewMoreOrders">查看更多</el-button>
            </div>
          </template>
          <el-table :data="recentOrders" style="width: 100%" :row-class-name="tableRowClassName">
            <el-table-column prop="orderNo" label="订单号" width="120" />
            <el-table-column prop="customerName" label="客户" />
            <el-table-column prop="amount" label="金额">
              <template #default="scope">
                <span>¥{{ scope.row.amount.toFixed(2) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getOrderStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="160" />
          </el-table>
        </el-card>
      </el-col>

      <!-- 最新用户 -->
      <el-col :xs="24" :lg="12">
        <el-card class="table-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最新用户</span>
              <el-button text @click="viewMoreUsers">查看更多</el-button>
            </div>
          </template>
          <el-table :data="recentUsers" style="width: 100%">
            <el-table-column prop="avatar" label="" width="50">
              <template #default="scope">
                <el-avatar :size="32" :src="scope.row.avatar">
                  {{ scope.row.username.charAt(0).toUpperCase() }}
                </el-avatar>
              </template>
            </el-table-column>
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="role" label="角色">
              <template #default="scope">
                <el-tag :type="getUserRoleType(scope.row.role)">
                  {{ getUserRoleText(scope.row.role) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="registerTime" label="注册时间" />
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button size="small" text @click="viewUserDetail(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="activity-row">
      <!-- 系统日志 -->
      <el-col :xs="24">
        <el-card class="system-logs" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>系统日志</span>
              <div class="card-actions">
                <el-button-group size="small">
                  <el-button :type="logType === 'all' ? 'primary' : ''" @click="logType = 'all'">全部</el-button>
                  <el-button :type="logType === 'system' ? 'primary' : ''" @click="logType = 'system'">系统</el-button>
                  <el-button :type="logType === 'login' ? 'primary' : ''" @click="logType = 'login'">登录</el-button>
                  <el-button :type="logType === 'operation' ? 'primary' : ''" @click="logType = 'operation'">操作</el-button>
                </el-button-group>
              </div>
            </div>
          </template>
          <el-timeline>
            <el-timeline-item
              v-for="(log, index) in filteredLogs"
              :key="index"
              :type="getLogTypeIcon(log.type)"
              :color="getLogTypeColor(log.type)"
              :timestamp="log.time"
              :hollow="true"
            >
              <div class="log-content">
                <span class="log-message">{{ log.message }}</span>
                <span class="log-user">{{ log.user }}</span>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  User, ShoppingCart, TrendCharts, Setting, CaretTop, CaretBottom,
  Calendar, Info, Warning, SuccessFilled
} from '@element-plus/icons-vue'
import homeApi from '@/api/home'
import { ElMessage } from 'element-plus'

export default {
  name: 'AdminDashboard',
  components: {
    User, ShoppingCart, TrendCharts, Setting, CaretTop, CaretBottom,
    Calendar, Info, Warning, SuccessFilled
  },
  setup() {
    const router = useRouter()
    
    // 数据卡片
    const statCards = ref([
      {
        icon: 'User',
        label: '总用户数',
        value: 0,
        progress: 0,
        progressText: '本月新增: 0',
        trend: 0,
        bgColor: 'rgba(64, 158, 255, 0.1)'
      },
      {
        icon: 'ShoppingCart',
        label: '总订单数',
        value: 0,
        progress: 0,
        progressText: '本月新增: 0',
        trend: 0,
        bgColor: 'rgba(103, 194, 58, 0.1)'
      },
      {
        icon: 'TrendCharts',
        label: '总收入',
        value: '¥0',
        progress: 0,
        progressText: '本月: ¥0',
        trend: 0,
        bgColor: 'rgba(230, 162, 60, 0.1)'
      },
      {
        icon: 'Setting',
        label: '定制申请',
        value: 0,
        progress: 0,
        progressText: '审核通过率: 0%',
        trend: 0,
        bgColor: 'rgba(245, 108, 108, 0.1)'
      }
    ])
    
    // 图表类型
    const orderChartType = ref('month')
    const userChartType = ref('role')
    
    // 最近订单
    const recentOrders = ref([])
    
    // 最新用户
    const recentUsers = ref([])
    
    // 系统日志
    const logType = ref('all')
    const systemLogs = ref([])
    
    // 过滤日志
    const filteredLogs = computed(() => {
      if (logType.value === 'all') {
        return systemLogs.value
      } else {
        return systemLogs.value.filter(log => log.type === logType.value)
      }
    })
    
    // 获取仪表盘数据
    const loadDashboardData = async () => {
      try {
        // 获取统计数据
        const statsRes = await homeApi.getHomeStats()
        if (statsRes.code === 200) {
          updateStatCards(statsRes.data)
        }
        
        // 获取最近订单
        const ordersRes = await homeApi.getRecentOrders()
        if (ordersRes.code === 200) {
          recentOrders.value = ordersRes.data
        }
        
        // 获取最新用户
        const usersRes = await homeApi.getRecentUsers()
        if (usersRes.code === 200) {
          recentUsers.value = usersRes.data
        }
        
        // 获取系统日志
        const logsRes = await homeApi.getSystemLogs()
        if (logsRes.code === 200) {
          systemLogs.value = logsRes.data
        }
      } catch (error) {
        console.error('加载仪表盘数据失败:', error)
        ElMessage.error('加载仪表盘数据失败，请稍后重试')
      }
    }
    
    // 更新统计卡片数据
    const updateStatCards = (stats) => {
      // 更新用户卡片
      statCards.value[0].value = stats.totalUsers
      statCards.value[0].progress = calculateProgress(stats.newUsersThisMonth, stats.totalUsers)
      statCards.value[0].progressText = `本月新增: ${stats.newUsersThisMonth}`
      statCards.value[0].trend = stats.userGrowth
      
      // 更新订单卡片
      statCards.value[1].value = stats.totalOrders
      statCards.value[1].progress = calculateProgress(stats.newOrdersThisMonth, stats.totalOrders)
      statCards.value[1].progressText = `本月新增: ${stats.newOrdersThisMonth}`
      statCards.value[1].trend = stats.orderGrowth
      
      // 更新收入卡片
      statCards.value[2].value = `¥${stats.totalIncome.toLocaleString()}`
      statCards.value[2].progress = calculateProgress(stats.thisMonthIncome, stats.totalIncome)
      statCards.value[2].progressText = `本月: ¥${stats.thisMonthIncome.toLocaleString()}`
      statCards.value[2].trend = stats.incomeGrowth
      
      // 更新定制申请卡片
      statCards.value[3].value = stats.customRequests
      statCards.value[3].progress = stats.approvalRate
      statCards.value[3].progressText = `审核通过率: ${stats.approvalRate}%`
      statCards.value[3].trend = 0 // 暂无趋势数据
    }
    
    // 计算进度百分比
    const calculateProgress = (part, total) => {
      if (total === 0) return 0
      return Math.min(Math.round((part / total) * 100), 100)
    }
    
    // 获取订单状态样式
    const getOrderStatusType = (status) => {
      const statusMap = {
        'PENDING_PAYMENT': 'warning',
        'PENDING_SHIPMENT': 'info',
        'IN_PRODUCTION': 'primary',
        'SHIPPED': 'success',
        'COMPLETED': 'success',
        'CANCELLED': 'info'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取用户角色样式
    const getUserRoleType = (role) => {
      const roleMap = {
        'admin': 'danger',
        'designer': 'warning',
        'user': 'info'
      }
      return roleMap[role] || 'info'
    }
    
    // 获取用户角色文本
    const getUserRoleText = (role) => {
      const roleMap = {
        'admin': '管理员',
        'designer': '设计师',
        'user': '普通用户'
      }
      return roleMap[role] || role
    }
    
    // 获取日志类型图标
    const getLogTypeIcon = (type) => {
      const typeMap = {
        'system': 'info',
        'login': 'success',
        'operation': 'warning'
      }
      return typeMap[type] || 'info'
    }
    
    // 获取日志类型颜色
    const getLogTypeColor = (type) => {
      const colorMap = {
        'system': '#909399',
        'login': '#67C23A',
        'operation': '#E6A23C'
      }
      return colorMap[type] || '#909399'
    }
    
    // 表格行样式
    const tableRowClassName = ({ row }) => {
      if (row.status === 'PENDING_PAYMENT') {
        return 'warning-row'
      } else if (row.status === 'CANCELLED') {
        return 'info-row'
      }
      return ''
    }
    
    // 查看更多订单
    const viewMoreOrders = () => {
      router.push('/admin/order/list')
    }
    
    // 查看更多用户
    const viewMoreUsers = () => {
      router.push('/admin/user/list')
    }
    
    // 查看用户详情
    const viewUserDetail = (user) => {
      router.push(`/admin/user/detail/${user.username}`)
    }
    
    // 切换日志类型
    const changeLogType = async (type) => {
      logType.value = type
      try {
        const res = await homeApi.getSystemLogs(type)
        if (res.code === 200) {
          systemLogs.value = res.data
        }
      } catch (error) {
        console.error('加载系统日志失败:', error)
      }
    }
    
    // 切换订单图表类型
    const changeOrderChartType = async (type) => {
      orderChartType.value = type
      // 这里应该加载图表数据
    }
    
    // 切换用户图表类型
    const changeUserChartType = async (type) => {
      userChartType.value = type
      // 这里应该加载图表数据
    }
    
    // 初始化数据
    onMounted(() => {
      loadDashboardData()
    })
    
    return {
      statCards,
      orderChartType,
      userChartType,
      recentOrders,
      recentUsers,
      logType,
      filteredLogs,
      getOrderStatusType,
      getUserRoleType,
      getUserRoleText,
      getLogTypeIcon,
      getLogTypeColor,
      tableRowClassName,
      viewMoreOrders,
      viewMoreUsers,
      viewUserDetail,
      changeLogType,
      changeOrderChartType,
      changeUserChartType
    }
  }
}
</script>

<style scoped>
.admin-dashboard {
  padding: 20px;
}

/* 数据卡片 */
.stat-card {
  height: 140px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-radius: 8px;
  transition: transform 0.3s, box-shadow 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 28px;
  opacity: 0.7;
}

.stat-info {
  margin-bottom: 16px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.stat-progress {
  margin-top: auto;
}

.progress-text {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.trend {
  display: flex;
  align-items: center;
}

.trend.up {
  color: #67C23A;
}

.trend.down {
  color: #F56C6C;
}

/* 图表卡片 */
.charts-row {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.chart-placeholder {
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f8f8f8;
  color: #999;
  border-radius: 4px;
}

.placeholder-text {
  font-size: 16px;
}

/* 表格卡片 */
.table-row {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

/* 系统日志 */
.activity-row {
  margin-bottom: 20px;
}

.system-logs {
  border-radius: 8px;
}

.log-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.log-message {
  flex: 1;
}

.log-user {
  margin-left: 16px;
  color: #666;
  font-size: 13px;
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-actions {
  display: flex;
  align-items: center;
}

/* 表格样式 */
:deep(.warning-row) {
  background-color: rgba(230, 162, 60, 0.1);
}

:deep(.info-row) {
  background-color: rgba(144, 147, 153, 0.1);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .admin-dashboard {
    padding: 10px;
  }
  
  .stat-card {
    height: 120px;
  }
  
  .stat-value {
    font-size: 20px;
  }
  
  .chart-placeholder {
    height: 200px;
  }
}
</style> 